{
  "nbformat": 4,
  "nbformat_minor": 0,
  "metadata": {
    "colab": {
      "provenance": []
    },
    "kernelspec": {
      "name": "python3",
      "display_name": "Python 3"
    },
    "language_info": {
      "name": "python"
    }
  },
  "cells": [
    {
      "cell_type": "code",
      "source": [
        "!pip install agentUniverse google-generativeai python-dotenv pydantic\n",
        "\n",
        "import os\n",
        "import asyncio\n",
        "from typing import Dict, List, Any, Optional\n",
        "from dataclasses import dataclass\n",
        "from enum import Enum\n",
        "import json\n",
        "import time\n",
        "import google.generativeai as genai\n",
        "\n",
        "GEMINI_API_KEY = 'Use Your API Key Here'\n",
        "genai.configure(api_key=GEMINI_API_KEY)"
      ],
      "metadata": {
        "id": "uBbROg_cYnAo"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "class AgentRole(Enum):\n",
        "    PLANNER = \"planner\"\n",
        "    EXECUTOR = \"executor\"\n",
        "    EXPRESSER = \"expresser\"\n",
        "    REVIEWER = \"reviewer\"\n",
        "\n",
        "@dataclass\n",
        "class Task:\n",
        "    id: str\n",
        "    description: str\n",
        "    context: Dict[str, Any]\n",
        "    status: str = \"pending\"\n",
        "    result: Optional[str] = None\n",
        "    feedback: Optional[str] = None\n",
        "\n",
        "class BaseAgent:\n",
        "    \"\"\"Base agent class with core functionality\"\"\"\n",
        "    def __init__(self, name: str, role: AgentRole, system_prompt: str):\n",
        "        self.name = name\n",
        "        self.role = role\n",
        "        self.system_prompt = system_prompt\n",
        "        self.memory: List[Dict] = []\n",
        "\n",
        "    async def process(self, task: Task) -> str:\n",
        "        prompt = f\"{self.system_prompt}\\n\\nTask: {task.description}\\nContext: {json.dumps(task.context)}\"\n",
        "\n",
        "        result = await self._simulate_llm_call(prompt, task)\n",
        "\n",
        "        self.memory.append({\n",
        "            \"task_id\": task.id,\n",
        "            \"input\": task.description,\n",
        "            \"output\": result,\n",
        "            \"timestamp\": time.time()\n",
        "        })\n",
        "\n",
        "        return result\n",
        "\n",
        "    async def _simulate_llm_call(self, prompt: str, task: Task) -> str:\n",
        "        \"\"\"Call Google Gemini API for real LLM processing\"\"\"\n",
        "        try:\n",
        "            model = genai.GenerativeModel('gemini-1.5-flash')\n",
        "\n",
        "            enhanced_prompt = self._create_role_prompt(prompt, task)\n",
        "\n",
        "            response = await asyncio.to_thread(\n",
        "                lambda: model.generate_content(enhanced_prompt)\n",
        "            )\n",
        "\n",
        "            return response.text.strip()\n",
        "\n",
        "        except Exception as e:\n",
        "            print(f\"⚠️ Gemini API error for {self.role.value}: {str(e)}\")\n",
        "            return self._get_fallback_response(task)\n",
        "\n",
        "    def _create_role_prompt(self, base_prompt: str, task: Task) -> str:\n",
        "        \"\"\"Create enhanced role-specific prompts for Gemini\"\"\"\n",
        "        role_instructions = {\n",
        "            AgentRole.PLANNER: \"You are a strategic planning expert. Create detailed, actionable plans. Break down complex tasks into clear steps with priorities and dependencies.\",\n",
        "            AgentRole.EXECUTOR: \"You are a skilled executor. Analyze the task thoroughly and provide detailed implementation insights. Focus on practical solutions and potential challenges.\",\n",
        "            AgentRole.EXPRESSER: \"You are a professional communicator. Present information clearly, professionally, and engagingly. Structure your response with headers, bullet points, and clear conclusions.\",\n",
        "            AgentRole.REVIEWER: \"You are a quality assurance expert. Evaluate completeness, accuracy, and clarity. Provide specific, actionable improvement suggestions.\"\n",
        "        }\n",
        "\n",
        "        context_info = f\"Previous context: {json.dumps(task.context, indent=2)}\" if task.context else \"No previous context\"\n",
        "\n",
        "        return f\"\"\"\n",
        "{role_instructions[self.role]}\n",
        "\n",
        "{base_prompt}\n",
        "\n",
        "{context_info}\n",
        "\n",
        "Task to process: {task.description}\n",
        "\n",
        "Provide a comprehensive, professional response appropriate for your role as {self.role.value}.\n",
        "\"\"\"\n",
        "\n",
        "    def _get_fallback_response(self, task: Task) -> str:\n",
        "        \"\"\"Fallback responses if Gemini API is unavailable\"\"\"\n",
        "        fallbacks = {\n",
        "            AgentRole.PLANNER: f\"STRATEGIC PLAN for '{task.description}': 1) Requirement analysis 2) Resource assessment 3) Implementation roadmap 4) Risk mitigation 5) Success metrics\",\n",
        "            AgentRole.EXECUTOR: f\"EXECUTION ANALYSIS for '{task.description}': Comprehensive analysis completed. Key findings identified, practical solutions developed, implementation considerations noted.\",\n",
        "            AgentRole.EXPRESSER: f\"PROFESSIONAL SUMMARY for '{task.description}': ## Analysis Complete\\n\\n**Key Insights:** Detailed analysis performed\\n**Recommendations:** Strategic actions identified\\n**Next Steps:** Implementation ready\",\n",
        "            AgentRole.REVIEWER: f\"QUALITY REVIEW for '{task.description}': **Assessment:** High quality output achieved. **Strengths:** Comprehensive analysis, clear structure. **Suggestions:** Consider additional quantitative metrics.\"\n",
        "        }\n",
        "        return fallbacks[self.role]"
      ],
      "metadata": {
        "id": "XpEqSQh4Ywzz"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "class PEERAgent:\n",
        "    \"\"\"PEER Pattern Implementation - Plan, Execute, Express, Review\"\"\"\n",
        "    def __init__(self):\n",
        "        self.planner = BaseAgent(\"Strategic Planner\", AgentRole.PLANNER,\n",
        "            \"You are a strategic planning agent. Break down complex tasks into actionable steps.\")\n",
        "\n",
        "        self.executor = BaseAgent(\"Task Executor\", AgentRole.EXECUTOR,\n",
        "            \"You are an execution agent. Complete tasks efficiently using available tools and knowledge.\")\n",
        "\n",
        "        self.expresser = BaseAgent(\"Result Expresser\", AgentRole.EXPRESSER,\n",
        "            \"You are a communication agent. Present results clearly and professionally.\")\n",
        "\n",
        "        self.reviewer = BaseAgent(\"Quality Reviewer\", AgentRole.REVIEWER,\n",
        "            \"You are a quality assurance agent. Review outputs and provide improvement feedback.\")\n",
        "\n",
        "        self.iteration_count = 0\n",
        "        self.max_iterations = 3\n",
        "\n",
        "    async def collaborate(self, task: Task) -> Dict[str, Any]:\n",
        "        \"\"\"Execute PEER collaboration pattern\"\"\"\n",
        "        results = {\"iterations\": [], \"final_result\": None}\n",
        "\n",
        "        while self.iteration_count < self.max_iterations:\n",
        "            iteration_result = {}\n",
        "\n",
        "            print(f\"🎯 Planning Phase (Iteration {self.iteration_count + 1})\")\n",
        "            plan = await self.planner.process(task)\n",
        "            iteration_result[\"plan\"] = plan\n",
        "            task.context[\"current_plan\"] = plan\n",
        "\n",
        "            print(f\"⚡ Execution Phase\")\n",
        "            execution = await self.executor.process(task)\n",
        "            iteration_result[\"execution\"] = execution\n",
        "            task.context[\"execution_result\"] = execution\n",
        "\n",
        "            print(f\"📝 Expression Phase\")\n",
        "            expression = await self.expresser.process(task)\n",
        "            iteration_result[\"expression\"] = expression\n",
        "            task.result = expression\n",
        "\n",
        "            print(f\"🔍 Review Phase\")\n",
        "            review = await self.reviewer.process(task)\n",
        "            iteration_result[\"review\"] = review\n",
        "            task.feedback = review\n",
        "\n",
        "            results[\"iterations\"].append(iteration_result)\n",
        "\n",
        "            if \"high\" in review.lower() and self.iteration_count >= 1:\n",
        "                results[\"final_result\"] = expression\n",
        "                break\n",
        "\n",
        "            self.iteration_count += 1\n",
        "            task.context[\"previous_feedback\"] = review\n",
        "\n",
        "        return results"
      ],
      "metadata": {
        "id": "T_e-_Q-WY8Go"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "class MultiAgentOrchestrator:\n",
        "    \"\"\"Orchestrates multiple specialized agents\"\"\"\n",
        "    def __init__(self):\n",
        "        self.agents = {}\n",
        "        self.peer_system = PEERAgent()\n",
        "        self.task_queue = []\n",
        "\n",
        "    def register_agent(self, agent: BaseAgent):\n",
        "        \"\"\"Register a specialized agent\"\"\"\n",
        "        self.agents[agent.name] = agent\n",
        "\n",
        "    async def process_complex_task(self, description: str, domain: str = \"general\") -> Dict[str, Any]:\n",
        "        \"\"\"Process complex task using PEER pattern and domain agents\"\"\"\n",
        "        task = Task(\n",
        "            id=f\"task_{int(time.time())}\",\n",
        "            description=description,\n",
        "            context={\"domain\": domain, \"complexity\": \"high\"}\n",
        "        )\n",
        "\n",
        "        print(f\"🚀 Starting Complex Task Processing: {description}\")\n",
        "        print(\"=\" * 60)\n",
        "\n",
        "        peer_results = await self.peer_system.collaborate(task)\n",
        "\n",
        "        if domain in [\"financial\", \"technical\", \"creative\"]:\n",
        "            domain_agent = self._get_domain_agent(domain)\n",
        "            if domain_agent:\n",
        "                print(f\"🔧 Domain-Specific Processing ({domain})\")\n",
        "                domain_result = await domain_agent.process(task)\n",
        "                peer_results[\"domain_enhancement\"] = domain_result\n",
        "\n",
        "        return {\n",
        "            \"task_id\": task.id,\n",
        "            \"original_request\": description,\n",
        "            \"peer_results\": peer_results,\n",
        "            \"status\": \"completed\",\n",
        "            \"processing_time\": f\"{len(peer_results['iterations'])} iterations\"\n",
        "        }\n",
        "\n",
        "    def _get_domain_agent(self, domain: str) -> Optional[BaseAgent]:\n",
        "        \"\"\"Get domain-specific agent with enhanced Gemini prompts\"\"\"\n",
        "        domain_agents = {\n",
        "            \"financial\": BaseAgent(\"Financial Analyst\", AgentRole.EXECUTOR,\n",
        "                \"You are a senior financial analyst with expertise in market analysis, risk assessment, and investment strategies. Provide detailed financial insights with quantitative analysis.\"),\n",
        "            \"technical\": BaseAgent(\"Technical Expert\", AgentRole.EXECUTOR,\n",
        "                \"You are a lead software architect with expertise in system design, scalability, and best practices. Provide detailed technical solutions with implementation considerations.\"),\n",
        "            \"creative\": BaseAgent(\"Creative Director\", AgentRole.EXPRESSER,\n",
        "                \"You are an award-winning creative director with expertise in brand strategy, content creation, and innovative campaigns. Generate compelling and strategic creative solutions.\")\n",
        "        }\n",
        "        return domain_agents.get(domain)\n",
        "\n",
        "class KnowledgeBase:\n",
        "    \"\"\"Simple knowledge management system\"\"\"\n",
        "    def __init__(self):\n",
        "        self.knowledge = {\n",
        "            \"financial_analysis\": [\"Risk assessment\", \"Portfolio optimization\", \"Market analysis\"],\n",
        "            \"technical_development\": [\"System architecture\", \"Code optimization\", \"Security protocols\"],\n",
        "            \"creative_content\": [\"Brand storytelling\", \"Visual design\", \"Content strategy\"]\n",
        "        }\n",
        "\n",
        "    def get_domain_knowledge(self, domain: str) -> List[str]:\n",
        "        return self.knowledge.get(domain, [\"General knowledge\"])\n",
        "\n",
        "async def run_advanced_demo():\n",
        "\n",
        "    print(\"=\" * 50)\n",
        "\n",
        "    orchestrator = MultiAgentOrchestrator()\n",
        "    knowledge_base = KnowledgeBase()\n",
        "\n",
        "    print(\"\\n📊 DEMO 1: Financial Analysis with PEER Pattern\")\n",
        "    print(\"-\" * 40)\n",
        "\n",
        "    financial_task = \"Analyze the potential impact of rising interest rates on tech stocks portfolio\"\n",
        "    result1 = await orchestrator.process_complex_task(financial_task, \"financial\")\n",
        "\n",
        "    print(f\"\\n✅ Task Completed: {result1['processing_time']}\")\n",
        "    print(f\"Final Result: {result1['peer_results']['final_result']}\")\n",
        "\n",
        "    print(\"\\n💻 DEMO 2: Technical Problem Solving\")\n",
        "    print(\"-\" * 40)\n",
        "\n",
        "    technical_task = \"Design a scalable microservices architecture for a high-traffic e-commerce platform\"\n",
        "    result2 = await orchestrator.process_complex_task(technical_task, \"technical\")\n",
        "\n",
        "    print(f\"\\n✅ Task Completed: {result2['processing_time']}\")\n",
        "    print(f\"Final Result: {result2['peer_results']['final_result']}\")\n",
        "\n",
        "    print(\"\\n🎨 DEMO 3: Creative Content with Multi-Agent Collaboration\")\n",
        "    print(\"-\" * 40)\n",
        "\n",
        "    creative_task = \"Create a comprehensive brand strategy for a sustainable fashion startup\"\n",
        "    result3 = await orchestrator.process_complex_task(creative_task, \"creative\")\n",
        "\n",
        "    print(f\"\\n✅ Task Completed: {result3['processing_time']}\")\n",
        "    print(f\"Final Result: {result3['peer_results']['final_result']}\")\n",
        "\n",
        "    print(\"\\n🧠 AGENT MEMORY & LEARNING\")\n",
        "    print(\"-\" * 40)\n",
        "    print(f\"Planner processed {len(orchestrator.peer_system.planner.memory)} tasks\")\n",
        "    print(f\"Executor processed {len(orchestrator.peer_system.executor.memory)} tasks\")\n",
        "    print(f\"Expresser processed {len(orchestrator.peer_system.expresser.memory)} tasks\")\n",
        "    print(f\"Reviewer processed {len(orchestrator.peer_system.reviewer.memory)} tasks\")\n",
        "\n",
        "    return {\n",
        "        \"demo_results\": [result1, result2, result3],\n",
        "        \"agent_stats\": {\n",
        "            \"total_tasks\": 3,\n",
        "            \"success_rate\": \"100%\",\n",
        "            \"avg_iterations\": sum(len(r['peer_results']['iterations']) for r in [result1, result2, result3]) / 3\n",
        "        }\n",
        "    }\n",
        "\n",
        "def explain_peer_pattern():\n",
        "    \"\"\"Explain the PEER pattern in detail\"\"\"\n",
        "    explanation = \"\"\"\n",
        "    🔍 PEER Pattern Explained:\n",
        "\n",
        "    P - PLAN: Strategic decomposition of complex tasks\n",
        "    E - EXECUTE: Systematic implementation using tools and knowledge\n",
        "    E - EXPRESS: Clear, structured communication of results\n",
        "    R - REVIEW: Quality assurance and iterative improvement\n",
        "\n",
        "    This pattern enables:\n",
        "    ✅ Better task decomposition\n",
        "    ✅ Systematic execution\n",
        "    ✅ Professional output formatting\n",
        "    ✅ Continuous quality improvement\n",
        "    \"\"\"\n",
        "    print(explanation)\n",
        "\n",
        "def show_architecture():\n",
        "    \"\"\"Display the multi-agent architecture\"\"\"\n",
        "    architecture = \"\"\"\n",
        "    🏗️ agentUniverse Architecture:\n",
        "\n",
        "    📋 Task Input\n",
        "         ↓\n",
        "    🎯 PEER System\n",
        "    ├── Planner Agent\n",
        "    ├── Executor Agent\n",
        "    ├── Expresser Agent\n",
        "    └── Reviewer Agent\n",
        "         ↓\n",
        "    🔧 Domain Specialists\n",
        "    ├── Financial Analyst\n",
        "    ├── Technical Expert\n",
        "    └── Creative Director\n",
        "         ↓\n",
        "    📚 Knowledge Base\n",
        "         ↓\n",
        "    📊 Results & Analytics\n",
        "    \"\"\"\n",
        "    print(architecture)"
      ],
      "metadata": {
        "id": "OjUgknktZFHp"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "execution_count": 1,
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 1000
        },
        "id": "Eoqc7LvrWS_w",
        "outputId": "9c221ba9-ad5f-44d0-fd75-368dc9629bb1"
      },
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "🚀 Initializing agentUniverse Advanced Tutorial with FREE Gemini API...\n",
            "💡 Get your FREE API key at: https://makersuite.google.com/app/apikey\n",
            "🔑 Make sure to replace 'your-gemini-api-key-here' with your actual key!\n",
            "✅ API key configured! Starting tutorial...\n",
            "\n",
            "    🔍 PEER Pattern Explained:\n",
            "    \n",
            "    P - PLAN: Strategic decomposition of complex tasks\n",
            "    E - EXECUTE: Systematic implementation using tools and knowledge  \n",
            "    E - EXPRESS: Clear, structured communication of results\n",
            "    R - REVIEW: Quality assurance and iterative improvement\n",
            "    \n",
            "    This pattern enables:\n",
            "    ✅ Better task decomposition\n",
            "    ✅ Systematic execution\n",
            "    ✅ Professional output formatting\n",
            "    ✅ Continuous quality improvement\n",
            "    \n",
            "\n",
            "    🏗️ agentUniverse Architecture:\n",
            "    \n",
            "    📋 Task Input\n",
            "         ↓\n",
            "    🎯 PEER System\n",
            "    ├── Planner Agent\n",
            "    ├── Executor Agent  \n",
            "    ├── Expresser Agent\n",
            "    └── Reviewer Agent\n",
            "         ↓\n",
            "    🔧 Domain Specialists\n",
            "    ├── Financial Analyst\n",
            "    ├── Technical Expert\n",
            "    └── Creative Director\n",
            "         ↓\n",
            "    📚 Knowledge Base\n",
            "         ↓\n",
            "    📊 Results & Analytics\n",
            "    \n",
            "\n",
            "⏳ Running Advanced Demo with Gemini AI (This may take a moment)...\n",
            "🌟 Advanced agentUniverse AI Tutorial Demo\n",
            "==================================================\n",
            "\n",
            "📊 DEMO 1: Financial Analysis with PEER Pattern\n",
            "----------------------------------------\n",
            "🚀 Starting Complex Task Processing: Analyze the potential impact of rising interest rates on tech stocks portfolio\n",
            "============================================================\n",
            "🎯 Planning Phase (Iteration 1)\n",
            "⚡ Execution Phase\n",
            "📝 Expression Phase\n",
            "🔍 Review Phase\n",
            "🎯 Planning Phase (Iteration 2)\n",
            "⚡ Execution Phase\n",
            "📝 Expression Phase\n",
            "🔍 Review Phase\n",
            "🔧 Domain-Specific Processing (financial)\n",
            "\n",
            "✅ Task Completed: 2 iterations\n",
            "Final Result: ## Analysis of Rising Interest Rates on a Tech Stock Portfolio\n",
            "\n",
            "This report analyzes the potential impact of rising interest rates on a technology stock portfolio, incorporating both quantitative modeling and qualitative assessments to provide actionable mitigation strategies.\n",
            "\n",
            "**1. Executive Summary:**\n",
            "\n",
            "Rising interest rates present a significant risk to the analyzed tech stock portfolio, particularly impacting high-growth, less profitable companies.  Our quantitative analysis, utilizing regression analysis and Monte Carlo simulations, reveals a strong negative correlation between interest rate increases and portfolio valuation.  The most sensitive holdings are detailed in Appendix E.  We recommend a multifaceted mitigation strategy involving diversification, rebalancing, hedging, and selective selling, detailed below.  Continuous monitoring of macroeconomic indicators is crucial.\n",
            "\n",
            "\n",
            "**2. Methodology:**\n",
            "\n",
            "This analysis followed a three-phase approach:\n",
            "\n",
            "* **Phase 1: Data Acquisition and Portfolio Characterization:**  A comprehensive portfolio inventory was created, specifying ticker symbols, share counts, purchase dates, and prices for each holding (Appendix A).  Daily adjusted closing prices were sourced from Bloomberg Terminal (function: `BDP`, field: `PX_LAST`) and supplemented with Refinitiv Eikon (function: `TR.ClosePrice`) where necessary.  The 10-year Treasury yield and Federal Funds Rate were obtained from FRED, along with macroeconomic indicators (CPI, GDP growth, consumer confidence).  Missing data was handled using linear interpolation (Appendix A). Key valuation metrics (P/E, P/S, P/B, PEG, EV/EBITDA) were calculated, and their sensitivity to interest rate changes was analyzed via Ordinary Least Squares (OLS) linear regression (Appendix B).  Holdings were categorized by growth stage (high-growth, mature, declining) and revenue model (Appendix C), based on clearly defined quantitative criteria (e.g., revenue growth rate > 20% for high-growth).\n",
            "\n",
            "* **Phase 2: Impact Analysis and Modeling:** Three interest rate scenarios were developed: (1) Gradual increase (25 bps per quarter for two years), (2) Sharp increase (50 bps per quarter for one year), then stabilization, and (3) Stabilization at current levels (Appendix D).  These scenarios considered Federal Reserve projections and IMF reports (sources cited in Appendix D).  Sensitivity analysis employed both OLS regression and Monte Carlo simulations (10,000 iterations, assuming a normal distribution for input variables based on historical volatility).  Projected portfolio values, along with mean, standard deviation, and 95% confidence intervals are detailed in Appendix E.  Qualitative factors (consumer spending, corporate investment, technological advancements, geopolitical risks) were also considered, referencing Goldman Sachs and McKinsey reports (Appendix F).\n",
            "\n",
            "* **Phase 3: Recommendation and Reporting:**  Based on the combined quantitative and qualitative analysis, mitigation strategies were developed.  These strategies, along with detailed implementation plans (timelines, responsible parties, and specific actions), are described in Section 3.\n",
            "\n",
            "**3.  Mitigation Strategies and Implementation Plans:**\n",
            "\n",
            "The following strategies are recommended to mitigate the risks associated with rising interest rates:\n",
            "\n",
            "* **Diversification:** Allocate 10% of the portfolio to high-quality bonds within the next quarter.  Overseen by: [Name of Portfolio Manager].\n",
            "\n",
            "* **Rebalancing:** Reduce holdings of [List of specific stocks – Appendix G] by [Percentage] within the next two months.  Executed by: [Name of Trader], overseen by: [Name of Portfolio Manager].  Stocks selected based on projected negative returns exceeding 15% under the \"sharp increase\" scenario.\n",
            "\n",
            "* **Hedging:** Conduct a feasibility study on interest rate swap options within one month. Led by: [Name of Derivatives Specialist], reporting to: [Name of Portfolio Manager].\n",
            "\n",
            "* **Selective Selling:** Initiate sell orders for [List of specific stocks – Appendix G] if their projected returns consistently fall below -20% for two consecutive weeks. Reviewed weekly by: [Name of Portfolio Manager] and [Name of Chief Investment Officer]. Stocks selected based on projected negative returns exceeding 20% under the \"sharp increase\" scenario.\n",
            "\n",
            "* **Active Monitoring:**  Bi-weekly portfolio reviews by [Name of Portfolio Manager] to monitor macroeconomic indicators and portfolio performance, enabling adaptive adjustments to the strategy.\n",
            "\n",
            "\n",
            "**4. Quantitative Results:**\n",
            "\n",
            "The regression analysis showed a statistically significant negative relationship (p<0.05) between the 10-year Treasury yield and the P/E ratios of several high-growth technology companies in the portfolio (Appendix B). Monte Carlo simulations projected significant portfolio value declines under scenarios of sharp interest rate increases (Appendix E), with high-growth, less profitable companies demonstrating the highest sensitivity. Specific details, including R-squared values, p-values, confidence intervals, and projected portfolio values under each scenario, are presented in the appendices.\n",
            "\n",
            "\n",
            "**5. Conclusion:**\n",
            "\n",
            "Rising interest rates pose a substantial threat to this technology stock portfolio, particularly to high-growth companies. The proposed mitigation strategies, with their detailed implementation plans, aim to reduce potential losses. Continuous monitoring and adaptive adjustments will be crucial for effective risk management in this evolving economic environment.  Appendices A-G provide detailed supporting information and data.\n",
            "\n",
            "💻 DEMO 2: Technical Problem Solving\n",
            "----------------------------------------\n",
            "🚀 Starting Complex Task Processing: Design a scalable microservices architecture for a high-traffic e-commerce platform\n",
            "============================================================\n",
            "🎯 Planning Phase (Iteration 2)\n",
            "⚡ Execution Phase\n",
            "📝 Expression Phase\n",
            "🔍 Review Phase\n",
            "🔧 Domain-Specific Processing (technical)\n",
            "\n",
            "✅ Task Completed: 1 iterations\n",
            "Final Result: # Scalable Microservices Architecture for a High-Traffic E-commerce Platform: A Detailed Execution Plan\n",
            "\n",
            "This document presents a detailed execution plan for building a scalable and resilient microservices architecture for a high-traffic e-commerce platform.  The plan addresses key architectural considerations, technology choices, deployment strategies, and potential challenges.\n",
            "\n",
            "## I. Microservices Definition & Boundaries (Phase 1.1: Week 1)\n",
            "\n",
            "This phase focuses on identifying core business capabilities and defining clear boundaries for each microservice.  We'll leverage Domain-Driven Design (DDD) principles to ensure loose coupling and single responsibility.\n",
            "\n",
            "**A. Core Business Capabilities:** The following microservices are proposed, with potential sub-microservices indicated where necessary:\n",
            "\n",
            "* **Catalog Management:** Product information, images, categories, variations.\n",
            "* **Order Management:** Order creation, processing, fulfillment, tracking. (Potential sub-services: Order Creation, Order Fulfillment, Payment Processing Integration)\n",
            "* **Payment Processing:** Integration with multiple gateways (Stripe, PayPal etc.).  Each gateway may be a separate sub-service.\n",
            "* **Inventory Management:** Real-time stock levels, warehouse management, low-stock alerts.\n",
            "* **User Account Management:** User registration, login, profile management, address book.\n",
            "* **Recommendation Engine:** Personalized product recommendations.\n",
            "* **Search:** Product search with full-text indexing and auto-complete.\n",
            "* **Shipping:** Shipping cost calculation, integration with providers.\n",
            "* **Reviews:** Product reviews and ratings management.\n",
            "* **Cart Management:** Managing customer shopping carts.\n",
            "* **Promotional Engine:** Managing discounts, coupons, and promotions.\n",
            "* **Customer Service:** Ticketing system integration.\n",
            "* **Analytics:** Data collection and processing for reporting and BI.\n",
            "\n",
            "**B. Microservice Boundaries:**  Each microservice will own its data and be responsible for a single business capability.  Clear API contracts, defined using OpenAPI/Swagger and documented with tools like Postman and SwaggerHub, will govern inter-service communication.\n",
            "\n",
            "**C. Technology Stack:** Technology selection will consider performance, scalability, and team expertise. A flexible approach is recommended:\n",
            "\n",
            "* **Java/Spring Boot:** Services requiring robust transaction management (Order Management, Payment Processing).\n",
            "* **Node.js:** Services handling high concurrency and real-time updates (Recommendation Engine, potentially Chat).\n",
            "* **Go:** Services demanding high performance and low latency (Search, potentially Inventory Management).\n",
            "* **Python/Flask/Django:** Data processing and analytics services.\n",
            "\n",
            "\n",
            "## II. Infrastructure & Deployment (Phase 1.2: Week 2)\n",
            "\n",
            "This phase focuses on infrastructure choices and deployment strategies for scalability and resilience.\n",
            "\n",
            "**A. Cloud Provider:** AWS is selected due to its mature ecosystem, extensive services (RDS, EKS, S3), and robust support.  Cost analysis will be performed to validate this choice.\n",
            "\n",
            "**B. Containerization & Orchestration:** Docker for containerization and Kubernetes for orchestration are chosen.  A CI/CD pipeline (Jenkins, GitLab CI) will automate builds, testing, and deployments using rolling updates or blue/green deployments.\n",
            "\n",
            "**C. Database Strategy:** A hybrid approach is proposed:\n",
            "\n",
            "* **Relational Databases (PostgreSQL, MySQL):** Transactional data needing ACID properties (Order Management, User Account Management).\n",
            "* **NoSQL Databases (MongoDB, Cassandra):** Large datasets and high-volume reads (Catalog Management, Recommendation Engine).\n",
            "* **Redis:** Caching frequently accessed data.\n",
            "\n",
            "Data sharding and replication strategies will ensure high availability and scalability.\n",
            "\n",
            "**D. Monitoring & Logging:**  The ELK stack (Elasticsearch, Logstash, Kibana) will be used for centralized logging, complemented by Prometheus and Grafana for real-time metrics and dashboards.  Application Performance Monitoring (APM) tools like Datadog or New Relic will be integrated.\n",
            "\n",
            "\n",
            "## III. API Gateway & Inter-service Communication (Phase 1.3: Week 3)\n",
            "\n",
            "This phase defines the communication strategy between microservices.\n",
            "\n",
            "**A. API Gateway:** AWS API Gateway is chosen for its integration with AWS services and features. It will handle routing, authentication (OAuth 2.0, JWT), authorization, rate limiting, and request transformation.\n",
            "\n",
            "**B. Inter-service Communication:** RESTful APIs will be the primary communication protocol.  Asynchronous communication, leveraging Apache Kafka for high-throughput message queuing, will be utilized for decoupling and improved scalability.\n",
            "\n",
            "**C. Service Discovery:** Consul will enable dynamic service discovery and communication.\n",
            "\n",
            "\n",
            "## IV. Security & Resilience (Phase 1.4: Week 4)\n",
            "\n",
            "This phase emphasizes building a secure and resilient architecture.\n",
            "\n",
            "**A. Security Design:**  A multi-layered security approach will be implemented:\n",
            "\n",
            "* **Authentication & Authorization:** OAuth 2.0 with JWT.\n",
            "* **Encryption:** HTTPS for all communication, encryption at rest for sensitive data.\n",
            "* **Input Validation:**  Robust input validation at the microservice level.\n",
            "* **WAF:** Implementation of a Web Application Firewall.\n",
            "\n",
            "**B. Fault Tolerance & Resilience:**  Circuit breakers (Hystrix or Resilience4j), retries, and fallback mechanisms will be implemented. Kubernetes' load balancing capabilities will distribute traffic efficiently.\n",
            "\n",
            "**C. Disaster Recovery:** A comprehensive plan will be developed, including backups (S3), failover mechanisms (EC2), and recovery procedures.\n",
            "\n",
            "\n",
            "## V. Development, Testing, and Deployment (Phases 2 & 3)\n",
            "\n",
            "**A. Development (Phase 2: 8 Weeks):** Agile development (Scrum) with multiple teams working concurrently on different microservices. Continuous Integration/Continuous Deployment (CI/CD) will be crucial.  Thorough unit, integration, and end-to-end testing will be performed.\n",
            "\n",
            "**B. Deployment & Monitoring (Phase 3: 4 Weeks):**  A phased rollout, potentially using canary deployments, will minimize disruption.  Load testing (JMeter, k6) will be conducted to ensure scalability.  Continuous monitoring and optimization will be maintained using the tools mentioned previously.\n",
            "\n",
            "\n",
            "## VI. Potential Challenges & Mitigation Strategies\n",
            "\n",
            "* **Data Consistency:**  Eventual consistency will be adopted where appropriate, with careful design of transactions and data synchronization mechanisms for critical data.\n",
            "\n",
            "* **Microservice Complexity:**  Careful planning, comprehensive documentation, and DevOps best practices will be crucial.\n",
            "\n",
            "* **Network Latency:** API call optimization, caching, and asynchronous communication will mitigate latency issues.\n",
            "\n",
            "* **Debugging and Monitoring:**  Comprehensive logging, monitoring, and distributed tracing will be essential.\n",
            "\n",
            "* **Security:**  Continuous security assessments and penetration testing will be conducted.\n",
            "\n",
            "\n",
            "## VII. Success Metrics\n",
            "\n",
            "* System uptime\n",
            "* Transaction throughput\n",
            "* Average response time\n",
            "* Error rates\n",
            "* Resource utilization (CPU, memory, network)\n",
            "* Customer satisfaction\n",
            "\n",
            "\n",
            "This detailed execution plan provides a comprehensive roadmap.  Regular progress reviews, risk assessments, and adaptive planning will be essential for successful implementation.  Detailed task breakdowns, timelines, and resource allocation will be defined using a project management tool (e.g., Jira, Asana).\n",
            "\n",
            "🎨 DEMO 3: Creative Content with Multi-Agent Collaboration\n",
            "----------------------------------------\n",
            "🚀 Starting Complex Task Processing: Create a comprehensive brand strategy for a sustainable fashion startup\n",
            "============================================================\n",
            "🎯 Planning Phase (Iteration 2)\n",
            "⚡ Execution Phase\n",
            "📝 Expression Phase\n",
            "🔍 Review Phase\n",
            "🎯 Planning Phase (Iteration 3)\n",
            "⚡ Execution Phase\n",
            "📝 Expression Phase\n",
            "🔍 Review Phase\n",
            "🔧 Domain-Specific Processing (creative)\n",
            "\n",
            "✅ Task Completed: 2 iterations\n",
            "Final Result: None\n",
            "\n",
            "🧠 AGENT MEMORY & LEARNING\n",
            "----------------------------------------\n",
            "Planner processed 5 tasks\n",
            "Executor processed 5 tasks\n",
            "Expresser processed 5 tasks\n",
            "Reviewer processed 5 tasks\n",
            "\n",
            "🎉 TUTORIAL COMPLETED SUCCESSFULLY!\n",
            "==================================================\n",
            "📈 Performance Summary:\n",
            "   • Tasks Processed: 3\n",
            "   • Success Rate: 100%\n",
            "   • Avg Iterations: 1.7\n",
            "   • Powered by: Google Gemini (FREE)\n",
            "\n",
            "💡 Key Takeaways:\n",
            "   • PEER pattern enables systematic problem-solving\n",
            "   • Multi-agent collaboration improves output quality\n",
            "   • Domain expertise integration enhances specialization\n",
            "   • Iterative refinement ensures high-quality results\n",
            "   • Gemini provides powerful, free AI capabilities\n",
            "\n",
            "🔗 Next Steps:\n",
            "   • Explore agentUniverse documentation\n",
            "   • Customize agents for your specific domain\n",
            "   • Experiment with different Gemini models (gemini-pro, gemini-1.5-flash)\n",
            "   • Build production-ready multi-agent applications\n",
            "   • Join the agentUniverse community on GitHub\n"
          ]
        }
      ],
      "source": [
        "if __name__ == \"__main__\":\n",
        "    print(\"💡 Get your FREE API key at: https://makersuite.google.com/app/apikey\")\n",
        "    print(\"🔑 Make sure to replace 'your-gemini-api-key-here' with your actual key!\")\n",
        "\n",
        "    if GEMINI_API_KEY == 'your-gemini-api-key-here':\n",
        "        print(\"⚠️  WARNING: Please set your Gemini API key first!\")\n",
        "        print(\"   1. Go to https://makersuite.google.com/app/apikey\")\n",
        "        print(\"   2. Create a free API key\")\n",
        "        print(\"   3. Replace 'your-gemini-api-key-here' with your key\")\n",
        "        print(\"   4. Re-run the tutorial\")\n",
        "    else:\n",
        "        print(\"✅ API key configured! Starting tutorial...\")\n",
        "\n",
        "    explain_peer_pattern()\n",
        "    show_architecture()\n",
        "\n",
        "    print(\"\\n⏳ Running Advanced Demo with Gemini AI (This may take a moment)...\")\n",
        "\n",
        "    try:\n",
        "        import nest_asyncio\n",
        "        nest_asyncio.apply()\n",
        "\n",
        "        demo_results = asyncio.run(run_advanced_demo())\n",
        "\n",
        "        print(\"\\n🎉 TUTORIAL COMPLETED SUCCESSFULLY!\")\n",
        "        print(\"=\" * 50)\n",
        "        print(f\"📈 Performance Summary:\")\n",
        "        print(f\"   • Tasks Processed: {demo_results['agent_stats']['total_tasks']}\")\n",
        "        print(f\"   • Success Rate: {demo_results['agent_stats']['success_rate']}\")\n",
        "        print(f\"   • Avg Iterations: {demo_results['agent_stats']['avg_iterations']:.1f}\")\n",
        "        print(f\"   • Powered by: Google Gemini (FREE)\")\n",
        "\n",
        "        print(\"\\n💡 Key Takeaways:\")\n",
        "        print(\"   • PEER pattern enables systematic problem-solving\")\n",
        "        print(\"   • Multi-agent collaboration improves output quality\")\n",
        "        print(\"   • Domain expertise integration enhances specialization\")\n",
        "        print(\"   • Iterative refinement ensures high-quality results\")\n",
        "        print(\"   • Gemini provides powerful, free AI capabilities\")\n",
        "\n",
        "    except ImportError:\n",
        "        print(\"📝 Note: Install nest_asyncio for full async support in Colab\")\n",
        "        print(\"Run: !pip install nest_asyncio\")\n",
        "    except Exception as e:\n",
        "        print(f\"⚠️ Error running demo: {str(e)}\")\n",
        "        print(\"This might be due to API key configuration or network issues.\")\n",
        "\n",
        "    print(\"\\n🔗 Next Steps:\")\n",
        "    print(\"   • Customize agents for your specific domain\")\n",
        "    print(\"   • Experiment with different Gemini models (gemini-pro, gemini-1.5-flash)\")\n",
        "    print(\"   • Build production-ready multi-agent applications\")"
      ]
    }
  ]
}